<template>
  <div class="app-container" style="height: 82vh; overflow-x: auto;" v-loading="loading">
    <el-form :model="queryParams" ref="queryRef" :inline="true" :rules="rules">

      <el-form-item label="时间基准">
        <el-radio-group v-model="queryParams.selectedEpt">
          <el-radio label="班次">班次</el-radio>
          <el-radio label="单日">单日</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="时间" prop="dataTime" label-width="40px">
        <WeekTimePicker type="date" :options="disabledOptions" v-model="queryParams.dataTime" :clearable="false" style="width: 130px"/>
      </el-form-item>

      <el-form-item label="设备ID" prop="machineId" label-width="60px">
            <el-select v-model="queryParams.machineId" placeholder="请选择设备ID" style="width: 120px">
              <el-option
                  v-for="dict in machineIdOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>

      <el-form-item label="显示基准">
        <el-checkbox-group v-model="queryParams.showBase">
          <el-checkbox key="group" label="B" disabled>时间稼动率</el-checkbox>
          <el-checkbox key="group" label="C">总DOWN机率</el-checkbox>
          <el-checkbox key="group" label="D">生产PM率</el-checkbox>
          <el-checkbox key="group" label="E">设备PM率</el-checkbox>
          <el-checkbox key="group" label="F">其他PM率</el-checkbox>
          <el-checkbox key="group" label="G">待机率</el-checkbox>
        </el-checkbox-group>
        <el-button style="margin-left: 20px;" type="primary" icon="Search" @click="getQueryData">查询</el-button>
      </el-form-item>
    </el-form>

    <template v-for="(item, index, qwe) in dataAll">
      <div ref="myChart" id="chart" v-if="item.tableData[0].title === '时间稼动率(%)'" style="height: 240px; margin-bottom: 10px; border: 1px solid #aaa; border-radius: 4px;">sdss</div>
      <div ref="myChart" id="chart" style="height: 260px; margin-bottom: 10px; border: 1px solid #aaa; border-radius: 4px;">vvv</div>
      <t-ag-grid
        :style="{ height: getHeight(item.tableData.length)}"
        style="margin-bottom: 10px;"
        class="add-margin"
        :column-defs="getColumns(qwe)"
        :row-data="item.tableData"
        :row-buffer="20"
        :header-height="0"
        align="center"
        :getRowStyle ="getRowStyle"
        :defaultColDef = "{
          suppressMenu:true,
          flex: 1
        }"
        @cell-clicked="onCellClicked($event, index, qwe)"
        header-align="center"
      />

    </template>
  </div>
</template>

<script setup name="TestPages">
  import moment from 'moment'
  import * as echarts from 'echarts'
  import { listINFO, getMachineAllListDiewa, actualColumns, columns, getTableData, chartOptios, _trendsTitle } from "./config"
  import { useRouter } from 'vue-router'

  const router = useRouter()

  const { proxy } = getCurrentInstance()

  const queryParams = reactive({
    dataTime: moment().subtract(1, 'days').format('YYYY-MM-DD'),
    machineId: '',
    selectedEpt: '班次',
    showBase: ['B', 'C', 'D', 'E', 'F', 'G']
  })
  const machineIdOptions = ref([])
  const loading = ref(false)
  const dataAll = ref([])
  const JumpDate = ref({})
  const myChart = ref()
  let chart = null

  const rules = {
    machineId: [{ required: true, message: "请选择设备ID", trigger: "input" }]
  }

  const props = defineProps({
    Diewa: {
      type: Object
    }
  })

  const getColumns = (idx) => {
    if(idx === 0 || (idx === 1 && queryParams.showBase.includes('C'))){
      return actualColumns
    } else {
      return columns
    }
  }

  const disabledOptions = {
    disabledDate (date) {
      return date && date.valueOf() > moment().valueOf()
    }
  }

  const getQueryData = () => {

    proxy.$refs.queryRef.validate(valid => {
      if(valid){
        loading.value = true
        listINFO({
          dataTime: moment(queryParams.dataTime).format('YYYY-MM-DD'),
          type: queryParams.selectedEpt === '单日' ? 'D' : 'S',
          machineId: queryParams.machineId,
          referenceList: queryParams.showBase
        }).then((res) => {
          let { targetData, jump } = getTableData(res)
          dataAll.value = targetData
          JumpDate.value = jump
          loading.value = false

          let getChartData = []
          for(let key in targetData) {
            if(key === 'B'){
              getChartData.push(targetData[key].tableData.slice(0, 4))
              getChartData.push(targetData[key].tableData.slice(-6))
            } else {
              getChartData.push(JSON.parse(JSON.stringify(targetData[key].tableData)))
            }
          }

          nextTick(() => {
            myChart.value?.forEach((item, index) => {

              item.mark = item.innerText

              chart = echarts.init(item)
              const resizeObserver = new ResizeObserver((entries, b) => {
                if(echarts.getInstanceByDom(item)){
                  echarts.getInstanceByDom(item).resize()
                }
              })
              resizeObserver.observe(item)
              echarts.getInstanceByDom(item).setOption(chartOptios(getChartData, index, moment(queryParams.dataTime).format("YYYY-MM-DD").slice(-5), queryParams.machineId), true)
            })
          })
        })
      }
    })
  }

  const getRowStyle = (params) => {
    if(params.rowIndex === 0){
      return {
        background: '#bdd7ee'
      }
    }
  }

  getMachineAllListDiewa().then((res) => {
    res.rows.forEach((item) => {
      machineIdOptions.value.push({
        label: item,
        value: item
      })
    })
  })

  const getHeight = (length) => {
    switch (length) {
      case 4:
        return '131px'
      case 6:
        return '195px'
      case 7:
        return '227px'
      case 8:
        return '259px'
      case 9:
        return '291px'
      case 10:
        return '323px'
      default:
        break
    }
  }

  const onCellClicked = ({ rowIndex, value, colDef }, byName, idx) => {

    if(rowIndex === 2 && colDef.field !== 'title' && colDef.field !== 'attribute15'){
      if(idx === 0 || (idx === 1 && queryParams.showBase.includes('C'))){
        if(!idx){
          router.push({
            path: '/timeAnalysis/oeeTimeHistory',
            state: {
              startTime: JumpDate.value[colDef.field],
              endTime: queryParams.selectedEpt === '班次' ? moment(JumpDate.value[colDef.field]).add(12, 'hours').format("YYYY-MM-DD HH:mm:ss") : moment(JumpDate.value[colDef.field]).add(1, 'days').format("YYYY-MM-DD HH:mm:ss"),
              productionTypeId: '叠瓦',
              topId: [queryParams.machineId],
              radioVal: '全部履历'
            }
          })
        } else {
          router.push({
            path: '/indexAnalyse/timeTarget/warnPlato',
            state: {
              startTime: JumpDate.value[colDef.field],
              endTime: queryParams.selectedEpt === '班次' ? moment(JumpDate.value[colDef.field]).add(12, 'hours').format("YYYY-MM-DD HH:mm:ss") : moment(JumpDate.value[colDef.field]).add(1, 'days').format("YYYY-MM-DD HH:mm:ss"),
              productionTypeId: '叠瓦焊机',
              selectedEpt: '设备线',
              topId: queryParams.machineId
            }
          })
        }
      }
    }
  }

  watch(() => props.Diewa, val => {

    queryParams.dataTime = val.dataTime
    queryParams.selectedEpt = val.selectedEpt
    queryParams.machineId = val.machineId

    getQueryData()

  }, { deep: true })
</script>

<style lang="less" scoped>
.el-radio {
  margin-right: 8px;
}

.el-checkbox {
  margin-right: 14px;
}
</style>

